// pages/welcome/index/index.js
var util = require('../../../utils/util.js')

const ald = require('../../../utils/ald-stat.js');

//小神推
const xst_app = require('../../../utils/pushsdk.js').pushSdk(App, 'App').App;
const xst_page = require('../../../utils/pushsdk.js').pushSdk(Page).Page;

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //是否显示授权弹窗
    getPhoneNumberChange: false,
    getnewPhoneNumberChange:false,
    user_name: '登录',
    order_count: 0,
    share_count: 0,
    zfNumber: 0,
    userID: '',
    userNumber: '',
    adviserNum: '',
    phone: '',
    user_img: 'http://css.tt.gzedu.com/qy_oucnet_com/wx_img/1_ico_26.png'
  },

  /** 
   * 解析手机号码/unionID
   */
  parsePhone(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber2',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          wx.setStorageSync('wx_name', res.data.nickName);
          wx.setStorageSync('wx_head', res.data.avatarUrl);
          this.setData({
            user_name: res.data.nickName,
            user_img: res.data.avatarUrl
          })
          this.getUserData();
          //判断unionID是否注册
          // wx.request({
          //   url: app.globalData.url + 'c=user&m=isRegister',
          //   data: {
          //     union_id: union_id
          //   },
          //   success: res => {
          //     wx.hideLoading();
          //     res = res.data;
          //     if (res.status == 200) {
          //       if (res.data.is_register == 0) {
          //         //未注册
          //         this.register();
          //       } else {
          //         //已注册
          //         wx.setStorageSync('user_id', res.data.user_id);
          //         app.globalData.userId = res.data.user_id;
          //         this.getUserData();
          //       }
          //     } else {
          //       wx.showToast({
          //         title: res.msg,
          //         icon: 'none'
          //       });
          //     }
          //   }
          // })
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },
  //注册提交
  register() {
    var that = this;
    var data;
    //邀请注册 
    if (wx.getStorageSync('userID')) {
      data = {
        "phone": wx.getStorageSync('phone'),
        "agentName": wx.getStorageSync('wx_name'),
        "id_number": wx.getStorageSync('userNumber'), //顾问编号
        "userId": wx.getStorageSync('userID'), //顾问ID
        "refId": wx.getStorageSync('userID'), // 1公司内部推荐 > 1职工注册
        "enterpriseId": 1 ,
        "union_id": wx.getStorageSync('union_id')
      }
    } else {
      //游客注册
      data = {
        "phone": wx.getStorageSync('phone'),
        "agentName": wx.getStorageSync('wx_name'),
        // "id_number": sjNumber,
        "union_id": wx.getStorageSync('union_id')
      }
    }
    wx.request({
      url: app.globalData.url + "c=user&m=register",
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: data,
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status === 200) {
          wx.setStorageSync('user', res.data);
          wx.setStorageSync('user_id', res.data.id);
          //注册成功后，上传头像和手机号码
          wx.showLoading({
            "title": "拼命请求中...",
            "mask": true
          });
          wx.request({
            url: app.globalData.url + 'c=user&m=keepWeChat',
            data: {
              user_id: res.data.id,
              wx_head: wx.getStorageSync('wx_head'),
              wx_name: wx.getStorageSync('wx_name')
            },
            success: res => {
              wx.hideLoading();
              res = res.data;
              if (res.status == 200) {
                // this.videoPlay();
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                })
              }
            }
          })
        } else {
          wx.showToast({
            "title": res.msg,
            "icon": "none"
          });
        }
      }
    });
  },

  //手机号码授权回调
  getPhoneNumber(e) {
    if (e.detail.iv && e.detail.encryptedData) {
      this.setData({
        'getnewPhoneNumberChange': false
      });
      this.parseNewPhone(e.detail.encryptedData, e.detail.iv);
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
    }
  },

  /**
    * 获取手机号
    */
  parseNewPhone(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber2',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //拿到电话号码
          this.setData({
            'phone': res.data.purePhoneNumber
          })
          wx.setStorageSync('phone', res.data.purePhoneNumber);

          //拉取用户信息
          this.getUserData();
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }

      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      tabBarData: {
        list: app.tabBar,
        current: 1,
        isIphoneX: isIphoneX
      }
    })

    if (wx.getStorageSync('wx_name')) {
      this.setData({
        user_name: wx.getStorageSync('wx_name'),
        user_img: wx.getStorageSync('wx_head')
      })
      this.getUserData(); //请求数据
    } else {
      this.havaUnionID();
    }

    
  },

  /**
  * 获取用户信息
  */
  getUserData() {
    if (!wx.getStorageSync('phone')) {
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.setData({
            getnewPhoneNumberChange: true
          });
        }
      })
    } else {
      wx.showLoading({
        title: '拼命加载中...',
      });
      //有电话号码
      var phone = wx.getStorageSync('phone'),
        wx_name = wx.getStorageSync('wx_name'),
        time_data = (Date.parse(new Date())) / 1000,
        string_data = '',
        csData = {};
      string_data = 'learn_center_id=8038&relation_phone=' + phone + '&appsecret=VHRNwY1IfNE8YljsbqMnYuubuuTvlisJ&time=' + time_data;
      console.log(string_data);
      var sign_data = util.sha1(string_data);
      csData = {
        'appid': 'YX_1iyn1224on',
        'sign': sign_data,
        'time': time_data,
        'learn_center_id': '8038',
        'relation_phone': phone

      }
      wx.request({
        url: 'https://api.emp.eenet.com/preparerelationapi/countStatic.html',
        data: csData,
        success: (res) => {
          res = res.data;
          if (res.status == 1) {
            console.log(res.data);
            this.setData({
              share_count: res.data.share_count,
              order_count: res.data.order_count,
              zfNumber: res.data.share_count * 5 + res.data.order_count * 1000
            })
            wx.hideLoading() ;
          } else {
            wx.showToast({
              title: '获取信息失败',
              icon: 'none'
            });
          }
        }
      })
    }

  },

  //检查是否是扫码进入
  checkLoad(options) {
    if (JSON.stringify(options) !== '{}') {
      app.globalData.enterpriseId = options.enterpriseId;
      app.globalData.refId = options.refId;
      app.globalData.idNumber = options.idNumber;
      wx.redirectTo({
        url: '/pages/welcome/applydesc/applydesc'
      });
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      let arrPara = scene.split("&")
      let arr = [];
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split("=");
        if (arr[0] == 'enterpriseId') {
          app.globalData.enterpriseId = arr[1];
        }
        if (arr[0] == 'refId') {
          app.globalData.refId = arr[1];
        }
        if (arr[0] == 'idNumber') {
          app.globalData.idNumber = arr[1];
        }
      }
      wx.redirectTo({
        url: '/pages/welcome/applydesc/applydesc'
      });
    }
  },


  havaPhone() {
    if (wx.getStorageSync('phone')) {
      // wx.redirectTo({
      //   url: '/pages/guidanceStudy/visitor_index/index'
      // });
    }
    //如果不存在手机号码，要求授权手机号码
    wx.login({
      success: res => {
        wx.setStorageSync('code', res.code);
        this.setData({
          getPhoneNumberChange: true
        });
      }
    })
  },

  havaUnionID() {
    if (wx.getStorageSync('union_id')) {
      // wx.redirectTo({
      //   url: '/pages/guidanceStudy/visitor_index/index'
      // });
    } else {
      //如果不存在union_id，要求授权union_id
      this.getSetting();
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
        }
      })
    }
  },

  //是否授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          this.setData({
            getPhoneNumberChange: true
          })
        } else {
          //授权过
          if (!(wx.getStorageSync('wx_name') && wx.getStorageSync('wx_head'))) {
            wx.getUserInfo({
              success: res => {
                wx.setStorageSync('wx_name', res.userInfo.nickName);
                wx.setStorageSync('wx_head', res.userInfo.avatarUrl);
              }
            });
          }
        }
      }
    })
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      this.parsePhone(e.detail.encryptedData, e.detail.iv);
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    console.log(res.target)
    return {
      title: '邀请您体验国开公开课',
      path: '/pages/student/index/index?userNumber=' + wx.getStorageSync('adviserNum') + '&userID=' + wx.getStorageSync('user_id'),
      imageUrl: 'http://css.tt.gzedu.com/qy_oucnet_com/wx_img/ewm.PNG'
    }
  }
})